Page({
  data: {
    parrot: {},
    comments: [],
    commentContent: '',
    tempImages: [],
    replyingTo: null,
    replyContent: '',
    loadingComments: false,
    hasMoreComments: true,
    commentPage: 0,
    commentPageSize: 10,
    errorRetryCount: 0,
    maxRetryCount: 3,
    errorMessage: '', // 错误消息
    showError: false, // 是否显示错误提示
    submittingComment: false, // 评论提交状态
    activeReplyId: null, // 当前激活的回复ID，用于控制输入框位置
    userAvatar: '/images/icons/avatar.png', // 用户头像，默认使用系统头像
    userNickname: '匿名用户', // 用户昵称，默认值
    tempAvatarPath: '' // 临时头像路径
  },

  onLoad(options) {
    const app = getApp()
    app.recordVisit('pages/detail/index', options.id)
    this.getParrotDetail(options.id)
    this.loadComments(options.id)
  },

  // 获取鹦鹉详情
  async getParrotDetail(id) {
    wx.showLoading({ title: '加载中' })
    try {
      const res = await wx.cloud.database()
        .collection('lalayingwu')
        .doc(id)
        .get()
      console.log('获取到的鹦鹉详情数据:', res.data)
      this.setData({
        parrot: {
          ...res.data,
          gender: this.formatGender(res.data.gender),
          images: res.data.images || [], // 确保images数组存在
          videos: (res.data.videos || []).map(video => ({
            url: video,
            poster: this.generateVideoPoster(video) // 生成预览图
          }))
        },
        showError: false // 成功时隐藏错误提示
      })
      console.log('设置后的parrot数据:', this.data.parrot)
    } catch (err) {
      console.error('获取详情失败:', err)
      this.showError('获取详情失败，请检查网络后重试')
    }
    wx.hideLoading()
  },

  // 格式化性别显示
  formatGender(gender) {
    const genderMap = {
      0: '公',
      1: '母',
      2: '未知'
    }
    return genderMap[gender] || gender
  },

  // 图片加载错误处理
  onImageError(e) {
    console.error('图片加载失败:', e.detail.errMsg)
    this.showError('图片加载失败，请检查网络')
  },

  // 生成视频预览图
  generateVideoPoster(videoUrl) {
    // 使用云存储URL参数截取第2秒作为封面
    return `${videoUrl}?x-oss-process=video/snapshot,t_2000,f_jpg,w_200,h_200`
  },

  // 视频播放事件
  onVideoPlay(e) {
    const currentTarget = e.currentTarget
    const videoContext = wx.createVideoContext(currentTarget.id, this)
    videoContext.requestFullScreen()
  },

  // 视频暂停事件
  onVideoPause(e) {
    const currentTarget = e.currentTarget
    const videoContext = wx.createVideoContext(currentTarget.id, this)
    videoContext.exitFullScreen()
  },

  // 视频加载错误处理
  onVideoError(e) {
    console.error('视频加载错误:', e.detail.errMsg)
    this.showError('视频加载失败，请检查网络')
  },

  // 预览视频
  previewVideo(e) {
    const url = e.currentTarget.dataset.url
    wx.previewMedia({
      sources: [{
        url: url,
        type: 'video'
      }]
    })
  },

  // 下拉刷新
  onPullDownRefresh() {
    Promise.all([
      this.getParrotDetail(this.data.parrot._id),
      this.loadComments(this.data.parrot._id)
    ]).finally(() => {
      wx.stopPullDownRefresh()
    })
  },
  
  // 页面上拉触底事件
  onReachBottom() {
    if (this.data.hasMoreComments && !this.data.loadingComments) {
      this.loadMoreComments()
    }
  },

  // 格式化时间
  formatTime(date) {
    if (!date) return ''
    const d = new Date(date)
    const year = d.getFullYear()
    const month = (d.getMonth() + 1).toString().padStart(2, '0')
    const day = d.getDate().toString().padStart(2, '0')
    const hours = d.getHours().toString().padStart(2, '0')
    const minutes = d.getMinutes().toString().padStart(2, '0')
    return `${year}-${month}-${day} ${hours}:${minutes}`
  },

  // 加载评论（带分页和错误重试）- 支持多级评论
  async loadComments(parrotId, isLoadMore = false) {
    if (this.data.loadingComments) return
    
    // 如果是加载更多但已经没有更多数据了
    if (isLoadMore && !this.data.hasMoreComments) {
      return
    }
    
    this.setData({ loadingComments: true })
    
    try {
      const page = isLoadMore ? this.data.commentPage + 1 : 0
      const skip = page * this.data.commentPageSize
      
      // 加载主评论
      const res = await wx.cloud.database()
        .collection('comments')
        .where({
          parrotId: parrotId,
          rootComment: null // 只加载主评论
        })
        .orderBy('createTime', 'desc')
        .skip(skip)
        .limit(this.data.commentPageSize)
        .get()
      
      // 检查是否还有更多数据
      const hasMore = res.data.length === this.data.commentPageSize
      
      // 递归加载所有层级的回复
      const commentsWithReplies = await Promise.all(res.data.map(async comment => {
        const allReplies = await this.loadAllReplies(comment._id)
        return {
          ...comment,
          createTime: this.formatTime(comment.createTime),
          replies: allReplies
        }
      }))
      
      // 合并评论数据
      const updatedComments = isLoadMore 
        ? [...this.data.comments, ...commentsWithReplies]
        : commentsWithReplies
      
      this.setData({
        comments: updatedComments,
        commentPage: page,
        hasMoreComments: hasMore,
        loadingComments: false,
        errorRetryCount: 0, // 重置错误重试计数
        showError: false // 成功时隐藏错误提示
      })
      
    } catch (err) {
      console.error('加载评论失败:', err)
      this.setData({ loadingComments: false })
      
      // 错误重试机制
      if (this.data.errorRetryCount < this.data.maxRetryCount) {
        this.setData({ 
          errorRetryCount: this.data.errorRetryCount + 1 
        })
        
        wx.showToast({
          title: `加载失败，正在重试 (${this.data.errorRetryCount}/${this.data.maxRetryCount})`,
          icon: 'none',
          duration: 1500
        })
        
        // 延迟重试
        setTimeout(() => {
          this.loadComments(parrotId, isLoadMore)
        }, 1000 * this.data.errorRetryCount) // 指数退避
      } else {
        this.showError('评论加载失败，请检查网络后重试')
      }
    }
  },
  
  // 递归加载所有层级的回复
  async loadAllReplies(rootCommentId, parentComment = null) {
    try {
      const repliesRes = await wx.cloud.database()
        .collection('comments')
        .where({
          rootComment: rootCommentId
        })
        .orderBy('createTime', 'asc')
        .get()
      
      if (repliesRes.data.length === 0) {
        return []
      }
      
      // 递归加载每个回复的子回复，并查询被回复评论的用户信息
      const repliesWithChildren = await Promise.all(repliesRes.data.map(async reply => {
        let replyToUser = null
        
        // 如果这个回复是回复其他评论的，查询被回复评论的用户信息
        if (reply.replyTo) {
          try {
            const replyToRes = await wx.cloud.database()
              .collection('comments')
              .doc(reply.replyTo)
              .get()
            
            if (replyToRes.data) {
              replyToUser = {
                nickname: replyToRes.data.nickname,
                avatarUrl: replyToRes.data.avatarUrl
              }
            }
          } catch (err) {
            console.error('查询被回复评论失败:', err)
          }
        }
        
        const childReplies = await this.loadAllReplies(reply._id, reply)
        return {
          ...reply,
          createTime: this.formatTime(reply.createTime),
          parentComment: parentComment ? {
            _id: parentComment._id,
            nickname: parentComment.nickname
          } : null,
          replyToUser: replyToUser, // 添加被回复用户信息
          replies: childReplies
        }
      }))
      
      return repliesWithChildren
    } catch (err) {
      console.error('加载回复失败:', err)
      return []
    }
  },
  
  // 加载更多评论
  loadMoreComments() {
    if (this.data.parrot._id && this.data.hasMoreComments && !this.data.loadingComments) {
      this.loadComments(this.data.parrot._id, true)
    }
  },

  // 评论输入处理
  onCommentInput(e) {
    this.setData({
      commentContent: e.detail.value
    })
  },

  // 头像选择事件处理
  onChooseAvatar(e) {
    const { avatarUrl } = e.detail
    this.setData({
      tempAvatarPath: avatarUrl,
      userAvatar: avatarUrl
    })
  },

  // 昵称输入事件处理
  onNicknameInput(e) {
    this.setData({
      userNickname: e.detail.value
    })
  },

  // 处理回复按钮点击
  handleReply(e) {
    const commentId = e.currentTarget.dataset.id
    
    // 查找评论或回复的用户名
    let replyingToNickname = ''
    let foundComment = null
    
    // 在主评论中查找
    foundComment = this.data.comments.find(c => c._id === commentId)
    if (foundComment) {
      replyingToNickname = foundComment.nickname
    } else {
      // 在回复中查找
      for (const comment of this.data.comments) {
        if (comment.replies) {
          const foundReply = this.findReplyInReplies(comment.replies, commentId)
          if (foundReply) {
            replyingToNickname = foundReply.nickname
            break
          }
        }
      }
    }
    
    this.setData({
      replyingTo: commentId,
      replyingToNickname: replyingToNickname,
      activeReplyId: commentId, // 设置当前激活的回复ID
      commentContent: '', // 清空输入内容
      tempImages: [] // 清空临时图片
    })
  },

  // 取消回复
  cancelReply() {
    this.setData({
      replyingTo: null,
      replyingToNickname: '',
      activeReplyId: null // 取消激活状态
    })
  },

  // 在回复列表中查找特定回复
  findReplyInReplies(replies, replyId) {
    for (const reply of replies) {
      if (reply._id === replyId) {
        return reply
      }
      if (reply.replies && reply.replies.length > 0) {
        const found = this.findReplyInReplies(reply.replies, replyId)
        if (found) {
          return found
        }
      }
    }
    return null
  },


  // 选择图片
  async chooseImages() {
    try {
      const res = await wx.chooseMedia({
        count: 9,
        mediaType: ['image'],
        sizeType: ['compressed']
      })
      this.setData({
        tempImages: [...this.data.tempImages, ...res.tempFiles.map(file => file.tempFilePath)]
      })
    } catch (err) {
      console.error('选择图片失败:', err)
      this.showError('选择图片失败，请检查权限设置')
    }
  },

  // 移除图片
  removeImage(e) {
    const index = e.currentTarget.dataset.index
    const tempImages = [...this.data.tempImages]
    tempImages.splice(index, 1)
    this.setData({ tempImages })
  },

  // 提交评论
  async submitComment() {
    if (!this.data.commentContent.trim()) {
      wx.showToast({ title: '请输入评论内容', icon: 'none' })
      return
    }

    // 防止重复提交
    if (this.data.submittingComment) return
    this.setData({ submittingComment: true })

    wx.showLoading({ title: '提交中...' })
    try {
      // 1. 上传图片到云存储
      const fileIDs = []
      if (this.data.tempImages.length > 0) {
        const uploadTasks = this.data.tempImages.map(tempFilePath => 
          wx.cloud.uploadFile({
            cloudPath: `comments/${Date.now()}-${Math.random().toString(36).substr(2, 8)}.jpg`,
            filePath: tempFilePath
          })
        )
        const uploadResults = await Promise.all(uploadTasks)
        fileIDs.push(...uploadResults.map(res => res.fileID))
      }

      // 2. 上传头像到云存储（如果用户选择了新头像）
      let avatarUrl = this.data.userAvatar
      if (this.data.tempAvatarPath && this.data.tempAvatarPath !== '/images/icons/avatar.png') {
        try {
          const avatarUploadResult = await wx.cloud.uploadFile({
            cloudPath: `avatars/${Date.now()}-${Math.random().toString(36).substr(2, 8)}.jpg`,
            filePath: this.data.tempAvatarPath
          })
          avatarUrl = avatarUploadResult.fileID
        } catch (err) {
          console.error('头像上传失败，使用临时路径:', err)
          // 如果上传失败，继续使用临时路径
        }
      }

      // 3. 提交评论数据
      // 确定 rootComment：如果是回复评论，需要找到最顶层的主评论
      let rootCommentId = null
      if (this.data.replyingTo) {
        // 查找被回复的评论，获取其 rootComment
        for (const comment of this.data.comments) {
          if (comment._id === this.data.replyingTo) {
            rootCommentId = comment._id // 如果是回复主评论，rootComment就是主评论ID
            break
          }
          if (comment.replies) {
            const foundReply = this.findReplyInReplies(comment.replies, this.data.replyingTo)
            if (foundReply) {
              rootCommentId = foundReply.rootComment || comment._id
              break
            }
          }
        }
      }

      const commentData = {
        parrotId: this.data.parrot._id,
        content: this.data.commentContent,
        images: fileIDs,
        nickname: this.data.userNickname,
        avatarUrl: avatarUrl,
        createTime: new Date(),
        likes: [],
        likedUsers: [],
        replyTo: this.data.replyingTo || null,
        rootComment: rootCommentId
      }

      await wx.cloud.database().collection('comments').add({
        data: commentData
      })

      // 4. 刷新评论列表并重置表单
      this.loadComments(this.data.parrot._id)
      this.setData({
        commentContent: '',
        tempImages: [],
        tempAvatarPath: '', // 清空临时头像路径
        replyingTo: null,
        replyingToNickname: '',
        replyContent: '',
        activeReplyId: null, // 重置激活的回复ID
        showError: false // 成功时隐藏错误提示
      })
      wx.showToast({ title: '评论成功' })
    } catch (err) {
      console.error('提交评论失败:', err)
      this.showError('评论提交失败，请检查网络后重试')
    } finally {
      wx.hideLoading()
      this.setData({ submittingComment: false })
    }
  },

  // 显示错误信息
  showError(message) {
    this.setData({
      errorMessage: message,
      showError: true
    })
    
    // 5秒后自动隐藏错误提示
    setTimeout(() => {
      if (this.data.showError) {
        this.setData({ showError: false })
      }
    }, 5000)
  },

  // 隐藏错误提示
  hideError() {
    this.setData({ showError: false })
  },

  // 重试操作
  retryOperation() {
    this.setData({ showError: false })
    if (this.data.parrot._id) {
      this.loadComments(this.data.parrot._id)
    }
  },

  // 预览图片
  previewImage(e) {
    console.log('预览图片完整事件数据:', e)
    console.log('预览图片事件数据集:', e.currentTarget.dataset)
    
    let urls = []
    const dataset = e.currentTarget.dataset
    
    // 处理三种数据格式：
    // 1. 图片数组(dataset.urls)
    // 2. 单图片URL(dataset.url) 
    // 3. 当前点击图片(dataset.current)
    if (Array.isArray(dataset.urls)) {
      urls = dataset.urls
    } else if (typeof dataset.url === 'string') {
      urls = [dataset.url]
    } else if (typeof dataset.current === 'string') {
      // 从评论图片点击时可能只有current
      const commentItem = this.data.comments.find(c => 
        c.images && c.images.includes(dataset.current)
      )
      urls = commentItem ? commentItem.images : [dataset.current]
    } else {
      console.error('无效的图片数据:', dataset)
      wx.showToast({ 
        title: '图片数据错误，请稍后再试', 
        icon: 'none',
        duration: 2000
      })
      return
    }

    const index = dataset.index || 0
    
    // 确保索引在有效范围内
    if (index < 0 || index >= urls.length) {
      console.error('无效的图片索引:', index)
      return
    }

    // 处理URL格式 - 使用云存储的真实URL处理
    const processedUrls = urls.map(url => {
      if (!url) return ''
      // 如果是云存储文件ID，直接使用
      if (url.startsWith('cloud://')) {
        return url
      }
      // 如果是相对路径或文件名，使用云存储API获取真实URL
      if (!url.startsWith('http')) {
        // 这里应该使用云存储的真实域名，但需要根据实际配置调整
        // 暂时保持原样，因为云存储文件ID可以直接用于预览
        return url
      }
      return url
    }).filter(url => url) // 过滤空URL

    if (processedUrls.length === 0) {
      console.error('没有有效的图片URL')
      wx.showToast({ title: '没有可预览的图片', icon: 'none' })
      return
    }

    wx.previewImage({
      current: processedUrls[index],
      urls: processedUrls
    })
  },

  // 滚动到指定区域
  scrollToSection(e) {
    const section = e.currentTarget.dataset.section
    this.setData({ currentSection: section })
    
    wx.pageScrollTo({
      selector: `#${section}`,
      duration: 300
    })
  },

  // 页面滚动事件
  onPageScroll(e) {
    const scrollTop = e.scrollTop
    const query = wx.createSelectorQuery()
    
    query.select('#video-section').boundingClientRect()
    query.select('#photos-section').boundingClientRect()
    query.select('#comments-section').boundingClientRect()
    
    query.exec(res => {
      const sections = [
        { id: 'video-section', top: res[0].top },
        { id: 'photos-section', top: res[1].top },
        { id: 'comments-section', top: res[2].top }
      ]
      
      // 找到当前最接近顶部的区域
      const closest = sections.reduce((prev, curr) => {
        return Math.abs(curr.top) < Math.abs(prev.top) ? curr : prev
      })
      
      if (this.data.currentSection !== closest.id) {
        this.setData({ currentSection: closest.id })
      }
    })
  },

  // 转发给朋友（右上角菜单）
  onShareAppMessage() {
    if (this.data.parrot && this.data.parrot._id) {
      return {
        title: `${this.data.parrot.breed} - 拉拉的鹦鹉小屋`,
        path: `/pages/detail/index?id=${this.data.parrot._id}`,
        imageUrl: this.data.parrot.mainImage
      }
    }
    return {
      title: '拉拉的鹦鹉小屋 - 专业的鹦鹉养殖',
      path: '/pages/index/index'
    }
  },

  // 分享到朋友圈（右上角菜单）
  onShareTimeline() {
    if (this.data.parrot && this.data.parrot._id) {
      return {
        title: `${this.data.parrot.breed} - 拉拉的鹦鹉小屋`,
        query: `id=${this.data.parrot._id}`,
        imageUrl: this.data.parrot.mainImage
      }
    }
    return {
      title: '拉拉的鹦鹉小屋 - 专业的鹦鹉养殖',
      query: ''
    }
  }
})
